package OptimalAlgorithm.Linkedlist;
//https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
public class ReverseKGroup {
    public ListNode reverseKGroup(ListNode head, int k) {
        int len = 0;
        ListNode cur = head;
        while (cur != null){
            len++;
            cur = cur.next;
        }
        cur = head;
        int n = len / k;//需要翻转n组
        ListNode newHead = new ListNode();
        ListNode prev = newHead;
        for (int i = 0; i < n; i++) {
            ListNode temp = cur;
            for (int j = 0; j < k; j++) {
                //头插
                ListNode nextNode = cur.next;//保存原组的下一个节点！
                cur.next = prev.next;
                prev.next = cur;
                cur = nextNode;
            }
            prev = temp;
        }
        prev.next = cur;
        return newHead.next;
    }
}
